//
//  KFRealCartVC.m
//  KafeeSale
//
//  Created by Liboom on 2025/6/9.
//

#import "KFRealCartVC.h"
#import "KFCategoryModel.h"
#import "KFCateCell.h"
#import "KFGoodsCell.h"
#import "KFQRPayCodeView.h"
#import "KFChoseGoodsView.h"
#import "KFSpecMakeView.h"
@interface KFRealCartVC ()<UITableViewDelegate, UITableViewDataSource>
// 数据源
@property (nonatomic, strong) NSArray<KFCategoryModel *> *categories;

// 界面元素
@property (nonatomic, strong) UITableView *leftTableView;   // 左侧分类列表
@property (nonatomic, strong) UITableView *rightTableView;  // 右侧商品列表

// 记录右侧滚动是否由左侧点击引起
@property (nonatomic, assign) BOOL isRightScrollTriggeredByLeft;
@property(nonatomic, strong) UIView *botView;
@property(nonatomic, strong) UIView *countView;
@property(nonatomic, strong) UILabel *totalPriceLab;
@property(nonatomic, strong) UILabel  *totalCountLab;
@property(nonatomic, strong) NSArray *hasAddGoods;
@property(nonatomic, strong) KFChoseGoodsView *cartView;
@end

@implementation KFRealCartVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    if (self.categories.count > 0) {
        [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
    [self getData];
    [self getBeans];
}
-(void)getBeans{
    NSString * url = [WorkUrl returnURL:Interface_For_Get_Beans_Data];
    [PGNetworkHelper GET:url parameters:nil cache:NO headers:[Mytools getHeaders] responseCache:nil success:^(id responseObject) {
        if ([responseObject[@"code"] integerValue]==200) {
            VicSingleObject * single = [VicSingleObject getInstance];
            single.beansList = responseObject[@"data"];
        }else{
            XHQHUDErrorText(responseObject[@"message"]);
        }
    } failure:^(id error) {
        XHQHUDErrorText(error[@"msg"]);
    }];
}
-(void)createOrder{
    KFQRPayCodeView * v = [[KFQRPayCodeView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:v];
    __weak typeof(v)weakV = v;
    v.payBlock = ^{
        [self qrPay];
        [weakV removeFromSuperview];
    };
}
-(void)qrPay{
    NSMutableArray * arr = [NSMutableArray new];
    VicSingleObject * single = [VicSingleObject getInstance];
    
    for (KFProductModel * mo in single.cartList) {
        if (mo.choseCount > 0) {
            NSMutableDictionary *goodsDict = [NSMutableDictionary dictionary];
            goodsDict[@"goodsId"] = mo.tid;
            goodsDict[@"num"] = @(mo.choseCount);
            goodsDict[@"remark"] = mo.localRemark ?: @"";
            
            // 添加豆子选择
            if (mo.selectedBeans && mo.selectedBeans.count > 0) {
                goodsDict[@"bean"] = mo.selectedBeans.firstObject;
            }
            
            // 添加规格（如果有选中的规格）
            if (mo.selectedSpecs && mo.selectedSpecs.count > 0) {
                KFDishSpecList *spec = mo.selectedSpecs.firstObject;
                goodsDict[@"spec"] = @{
                    @"specId": spec.tid ?: @"",
                    @"specName": spec.specName ?: @"",
                    @"amount": [NSString stringWithFormat:@"%.2lf", spec.specPrice]
                };
            }
            
            // 添加做法（多选，需要判空）
            if (mo.selectedPractices && mo.selectedPractices.count > 0) {
                NSMutableArray *cooksItems = [NSMutableArray array];
                for (NSDictionary *practice in mo.selectedPractices) {
                    // 处理cooksPrice，确保始终传数字0而不是空字符串
                    id cookPriceValue = practice[@"cookPrice"];
                    NSNumber *cookPriceNumber = @0; // 默认值为0
                    
                    if (cookPriceValue) {
                        if ([cookPriceValue isKindOfClass:[NSNumber class]]) {
                            cookPriceNumber = cookPriceValue;
                        } else if ([cookPriceValue isKindOfClass:[NSString class]]) {
                            NSString *cookPriceString = (NSString *)cookPriceValue;
                            if (cookPriceString.length > 0) {
                                cookPriceNumber = @([cookPriceString floatValue]);
                            }
                        }
                    }
                    
                    [cooksItems addObject:@{
                        @"cooksPrice": cookPriceNumber,
                        @"cooksName": practice[@"cookName"] ?: @""
                    }];
                }
                
                // 使用从 KFSpecMakeView 传递过来的做法标题
                NSString *cooksTitle = @"做法";
                if (mo.practiceTitles && mo.practiceTitles.count > 0) {
                    cooksTitle = mo.practiceTitles.firstObject ?: @"做法";
                }
                
                goodsDict[@"cooks"] = @{
                    @"cooksTitle": cooksTitle,
                    @"cooksItems": cooksItems
                };
            }
            
            [arr addObject:goodsDict];
        }
    }
    
    NSDictionary *dic = nil;
    if (self.orderId) {
        dic = @{
            @"customerId": [Mytools getUserId],
            @"boardId": self.boardId,
            @"goods": arr,
            @"orderId": @(self.orderId),
            @"dinnerCount": @1
        };
    } else {
        dic = @{
            @"customerId": [Mytools getUserId],
            @"boardId": self.boardId,
            @"goods": arr,
            @"dinnerCount": @1
        };
    }
    
    XHQHUDInView(self.view);
    [PGNetworkHelper POST:[WorkUrl returnURL:Interface_For_Create_Order] parameters:dic cache:NO headers:[Mytools getHeaders] responseCache:nil success:^(id responseObject) {
        XHQHUDHide();
        if ([responseObject[@"code"] integerValue]==200) {
            [single.cartList removeAllObjects];
            XHQHUDSuccessText(@"下单成功");
            [self.navigationController popViewControllerAnimated:YES];
            dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 1*NSEC_PER_SEC);
            dispatch_after(time, dispatch_get_main_queue(), ^{
                if (self.backBlock) {
                    self.backBlock();
                }
            });
        }else{
            XHQHUDErrorText(responseObject[@"msg"]);
        }
    } failure:^(id error) {
        XHQHUDHide();
    }];
}
-(void)getData{
    XHQHUDInView(self.view);
    [PGNetworkHelper GET:[WorkUrl returnURL:Interface_For_CART_LIST] parameters:nil cache:NO headers:[Mytools getHeaders] responseCache:nil success:^(id responseObject) {
        XHQHUDHide();
        if ([responseObject[@"code"] integerValue] == 200) {
            NSArray *arr = [KFCategoryModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            self.categories = arr;
            [self.leftTableView reloadData];
            [self.rightTableView reloadData];
            if (self.categories.count > 0) {
                [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
            }
        } else {
            NSString *msg = responseObject[@"msg"] ?: @"数据加载失败";
            XHQHUDErrorText(msg);
        }
    } failure:^(id error) {
        XHQHUDHide();
    }];
}

- (void)setupUI {
    self.myTitle = @"点单";
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 1. 左侧分类列表 (宽度: 100)
    self.leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kTopHeight, 100, SCREEN_HEIGHT-kTopHeight-KTabbarSafeBottomMargin) style:UITableViewStylePlain];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.showsVerticalScrollIndicator = NO;
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.leftTableView];
    
    // 2. 右侧商品列表 (剩余宽度)
    CGFloat rightX = CGRectGetMaxX(self.leftTableView.frame);
    self.rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(rightX, kTopHeight, SCREEN_WIDTH - rightX, SCREEN_HEIGHT-kTopHeight-KTabbarSafeBottomMargin) style:UITableViewStyleGrouped];
    self.rightTableView.delegate = self;
    self.rightTableView.dataSource = self;
    self.rightTableView.sectionHeaderHeight = 40;
    self.rightTableView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
    [self.view addSubview:self.rightTableView];
    
    // 3. 注册cell
    [self.leftTableView registerClass:[KFCateCell class] forCellReuseIdentifier:@"KFCateCell"];
    [self.rightTableView registerClass:[KFGoodsCell class] forCellReuseIdentifier:@"KFGoodsCell"];
    
    self.botView = [UIView new];
    self.botView.cornerRadius = 25;
    self.botView.hidden = YES; // 初始状态为隐藏
    [self.botView addTarget:self action:@selector(showCartClick)];
    self.botView.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1];
    [self.view addSubview:self.botView];
    self.botView.sd_layout.leftSpaceToView(self.view, 20).rightSpaceToView(self.view, 20).bottomSpaceToView(self.view, KTabbarSafeBottomMargin+30).heightIs(50);
    UIButton * cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cartBtn addTarget:self action:@selector(showCartClick) forControlEvents:UIControlEventTouchUpInside];
    [cartBtn setImage:[UIImage imageNamed:@"购物车"] forState:UIControlStateNormal];
    [self.botView addSubview:cartBtn];
    cartBtn.sd_layout.centerYEqualToView(self.botView).widthIs(45).heightEqualToWidth().leftSpaceToView(self.botView, 0);
    
    UIButton * orderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    orderBtn.backgroundColor = [UIColor colorWithRed:0.85 green:0.87 blue:0.5 alpha:1];
    [orderBtn setTitle:@"下单" forState:UIControlStateNormal];
    [orderBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [orderBtn addTarget:self action:@selector(createOrder) forControlEvents:UIControlEventTouchUpInside];
    [self.botView addSubview:orderBtn];
    orderBtn.sd_layout.rightEqualToView(self.botView).topEqualToView(self.botView).bottomEqualToView(self.botView).widthIs(100);
    orderBtn.sd_cornerRadius = @0.5;
    
    self.totalPriceLab = [UILabel labelWithTitle:@"" color:RED_COLOR fontSize:25];
    [self.botView addSubview:self.totalPriceLab];
    self.totalPriceLab.sd_layout.leftSpaceToView(self.botView, 60).centerYEqualToView(self.botView).heightIs(20);
    [self.totalPriceLab setSingleLineAutoResizeWithMaxWidth:300];
    
    self.countView = [UIView new];
    self.countView.backgroundColor = RED_COLOR;
    self.countView.cornerRadius = 10;
    self.countView.hidden = YES;
    [self.view addSubview:self.countView];
    self.countView.sd_layout.centerXIs(60).bottomSpaceToView(self.view, KTabbarSafeBottomMargin+60).heightIs(20);
    
    self.totalCountLab = [UILabel labelWithTitle:@"1" color:UIColor.whiteColor fontSize:13];
    [self.countView addSubview:self.totalCountLab];
    self.totalCountLab.sd_layout.leftSpaceToView(self.countView, 7).topEqualToView(self.countView).bottomEqualToView(self.countView);
    [self.totalCountLab setSingleLineAutoResizeWithMaxWidth:300];
    [self.countView setupAutoWidthWithRightView:self.totalCountLab rightMargin:7];
    
}
-(void)showCartClick{
    VicSingleObject *single = [VicSingleObject getInstance];
    self.cartView = [[KFChoseGoodsView alloc]initWithFrame:Frame(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.cartView.dataArr = single.cartList;
    MJWeakSelf
    self.cartView.closeBlock = ^{
        DLLog(@"购物车数据: %@", single.cartList);
        [weakSelf recalculateProductChoseCounts];
        // 刷新UI
        [weakSelf.rightTableView reloadData];
        [weakSelf calTotalPrice];
        
        [weakSelf.cartView removeFromSuperview];
        weakSelf.cartView = nil;
    };
    
    self.cartView.orderDownBlock = ^{
        [weakSelf createOrder];
    };
    
    // 添加商品选择回调
    self.cartView.selectGoodsBlock = ^(KFProductModel *product) {
        // 弹出规格选择视图
        KFSpecMakeView *specMakeView = [[KFSpecMakeView alloc] initWithFrame:weakSelf.view.bounds model:product];
        
        specMakeView.confirmBlock = ^(NSInteger quantity, NSArray *selectedSpecs, NSArray *selectedPractices, NSArray *selectedBeans, NSArray *practiceTitles) {
            // 更新商品信息
            product.choseCount = quantity;
            product.selectedSpecs = selectedSpecs;
            product.selectedPractices = selectedPractices;
            product.selectedBeans = selectedBeans;
            product.practiceTitles = practiceTitles;
            
            // 同步到购物车
            [weakSelf syncProductToCart:product];
            
            // 刷新购物车和总价
            [weakSelf calTotalPrice];
            [weakSelf.rightTableView reloadData];
        };
        
        specMakeView.closeBlock = ^{
            // 关闭规格选择视图后，重新显示购物车视图
            [weakSelf showCartClick];
        };
        
        [specMakeView showInView:weakSelf.view];
    };
    
    [self.view addSubview:self.cartView];
}
- (void)recalculateProductChoseCounts {
    VicSingleObject *single = [VicSingleObject getInstance];
    
    // 先重置所有商品的数量为0
    for (KFCategoryModel *category in self.categories) {
        for (KFProductModel *product in category.goods) {
            product.choseCount = 0;
            product.selectedSpecs = @[];
            product.selectedPractices = @[];
            product.selectedBeans = @[];
        }
    }
    
    // 遍历购物车，累加相同商品的数量（按商品ID累加，不考虑规格做法）
    for (KFProductModel *cartProduct in single.cartList) {
        for (KFCategoryModel *category in self.categories) {
            for (KFProductModel *product in category.goods) {
                if ([product.tid isEqualToString:cartProduct.tid]) {
                    // 累加数量
                    product.choseCount += cartProduct.choseCount;
                    
                    // 对于没有规格做法的商品，保留购物车中的选择状态
                    if (product.cooksList.count == 0 && product.specList.count == 0) {
                        product.selectedSpecs = cartProduct.selectedSpecs;
                        product.selectedPractices = cartProduct.selectedPractices;
                        product.selectedBeans = cartProduct.selectedBeans;
                    }
                    break;
                }
            }
        }
    }
    
}
- (void)syncCartDataToProductList {
    VicSingleObject *single = [VicSingleObject getInstance];
    
    // 先重置所有商品的数量为0
    for (KFCategoryModel *category in self.categories) {
        for (KFProductModel *product in category.goods) {
            product.choseCount = 0;
        }
    }
    
    // 遍历购物车，累加相同商品的数量（不考虑规格做法，只按商品ID累加）
    for (KFProductModel *cartProduct in single.cartList) {
        for (KFCategoryModel *category in self.categories) {
            for (KFProductModel *product in category.goods) {
                if ([product.tid isEqualToString:cartProduct.tid]) {
                    // 累加数量
                    product.choseCount += cartProduct.choseCount;
                    break;
                }
            }
        }
    }
}
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.leftTableView) {
        return 1;
    }
    return self.categories.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.leftTableView) {
        return self.categories.count;
    }
    KFCategoryModel *category = self.categories[section];
    return category.goods.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.leftTableView) {
        KFCateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KFCateCell"];
        if (!cell) {
            cell = [[KFCateCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"KFCateCell"];
        }
        KFCategoryModel *category = self.categories[indexPath.row];
        cell.model = category;
        return cell;
    }
    else {
        KFGoodsCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"KFGoodsCell"];
        if (!cell) {
            cell = [[KFGoodsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"KFGoodsCell"];
        }
        __weak typeof(self)weakSelf = self;
        cell.actionBtnBlock = ^(NSString * _Nonnull price) {
            [weakSelf calTotalPrice];
        };
        KFCategoryModel *category = self.categories[indexPath.section];
        KFProductModel *product = category.goods[indexPath.row];
        cell.model = product;
        return cell;
    }
}
- (void)syncProductToCart:(KFProductModel *)product {
    VicSingleObject *single = [VicSingleObject getInstance];
    
    // 检查购物车中是否已存在相同商品
    BOOL exists = NO;
    for (KFProductModel *cartProduct in single.cartList) {
        if ([self isSameProduct:cartProduct with:product]) {
            // 更新数量
            cartProduct.choseCount = product.choseCount;
            exists = YES;
            break;
        }
    }
    
    // 如果不存在，添加到购物车
    if (!exists && product.choseCount > 0) {
        // 创建商品副本
        KFProductModel *cartCopy = [[KFProductModel alloc] init];
        cartCopy.tid = product.tid;
        cartCopy.name = product.name;
        cartCopy.price = product.price;
        cartCopy.choseCount = product.choseCount;
        cartCopy.localRemark = product.localRemark;
        cartCopy.selectedSpecs = [product.selectedSpecs copy];
        cartCopy.selectedPractices = [product.selectedPractices copy];
        cartCopy.selectedBeans = [product.selectedBeans copy];
        cartCopy.practiceTitles = [product.practiceTitles copy];
        
        [single.cartList addObject:cartCopy];
    }
}
// 判断是否为相同商品（考虑规格、做法、豆子）
- (BOOL)isSameProduct:(KFProductModel *)model1 with:(KFProductModel *)model2 {
    if (![model1.tid isEqualToString:model2.tid]) {
        return NO;
    }
    
    // 比较规格
    if (model1.selectedSpecs.count != model2.selectedSpecs.count) {
        return NO;
    }
    
    for (int i = 0; i < model1.selectedSpecs.count; i++) {
        KFDishSpecList *spec1 = model1.selectedSpecs[i];
        KFDishSpecList *spec2 = model2.selectedSpecs[i];
        if (![spec1.specName isEqualToString:spec2.specName] || spec1.specPrice != spec2.specPrice) {
            return NO;
        }
    }
    
    // 比较做法
    if (model1.selectedPractices.count != model2.selectedPractices.count) {
        return NO;
    }
    
    for (int i = 0; i < model1.selectedPractices.count; i++) {
        NSDictionary *practice1 = model1.selectedPractices[i];
        NSDictionary *practice2 = model2.selectedPractices[i];
        if (![practice1[@"cookName"] isEqualToString:practice2[@"cookName"]] ||
            [practice1[@"cookPrice"] floatValue] != [practice2[@"cookPrice"] floatValue]) {
            return NO;
        }
    }
    
    // 比较豆子
    if (![model1.selectedBeans isEqualToArray:model2.selectedBeans]) {
        return NO;
    }
    
    return YES;
}

-(void)calTotalPrice{
    CGFloat price = 0;
    NSInteger count = 0;
    VicSingleObject *single = [VicSingleObject getInstance];
    
    // 直接遍历购物车计算总价
    for (KFProductModel *product in single.cartList) {
        if (product.choseCount > 0) {
            // 计算当前商品总价：基础价格 + 规格价格 + 做法价格
            CGFloat basePrice = product.price;
            
            // 加上规格价格（如果有选中的规格）
            if (product.selectedSpecs && product.selectedSpecs.count > 0) {
                KFDishSpecList *spec = product.selectedSpecs.firstObject;
                basePrice += spec.specPrice;
            }
            
            // 加上做法价格（多选）
            if (product.selectedPractices && product.selectedPractices.count > 0) {
                for (NSDictionary *practice in product.selectedPractices) {
                    CGFloat practicePrice = [practice[@"cookPrice"] floatValue];
                    basePrice += practicePrice;
                }
            }
            
            price += basePrice * product.choseCount;
            count += product.choseCount;
        }
    }
        
    self.totalPriceLab.text = [NSString stringWithFormat:@"￥%.0lf", price];
    if(count > 0){
        self.countView.hidden = NO;
        self.totalCountLab.text = [NSString stringWithFormat:@"%ld", count];
        self.botView.hidden = NO; // 有商品时显示底部视图
    } else {
        self.countView.hidden = YES;
        self.botView.hidden = YES; // 没有商品时隐藏底部视图
    }
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == self.rightTableView) {
        UIView * bgView = [UIView new];
        bgView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
        UILabel * titleLab = [UILabel labelWithTitle:self.categories[section].categoryName color:[UIColor blackColor] font:[UIFont systemFontOfSize:24]];
        [bgView addSubview:titleLab];
        titleLab.sd_layout.leftSpaceToView(bgView, 10).centerYEqualToView(bgView).heightIs(30);
        [titleLab setSingleLineAutoResizeWithMaxWidth:300];
        return bgView;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.rightTableView){
        return 80;
    }
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section < self.categories.count - 1){
        return 0.01;
    }
    return KTabbarSafeBottomMargin+80;
}
// 左侧表格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.leftTableView) {
        return 60;
    }
    KFCategoryModel *category = self.categories[indexPath.section];
    KFProductModel *product = category.goods[indexPath.row];
    return [self.rightTableView cellHeightForIndexPath:indexPath model:product keyPath:@"model" cellClass:[KFGoodsCell class]  contentViewWidth:SCREEN_WIDTH];
}

// 左侧表格选中时滚动到右侧对应分类位置
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.leftTableView) {
        // 标记右侧滚动由左侧点击引起
        self.isRightScrollTriggeredByLeft = YES;
        // 检查该分类下是否有商品
        KFCategoryModel *selectedCategory = self.categories[indexPath.row];
        NSInteger goodsCount = selectedCategory.goods.count;
        if (goodsCount > 0) {
            // 有商品时才滚动
            [self.rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.row]
                                     atScrollPosition:UITableViewScrollPositionTop
                                             animated:YES];
        } else {
            // 无商品时取消选中并提示（可选）
            [self.leftTableView deselectRowAtIndexPath:indexPath animated:YES];
            // 如果需要提示用户
            XHQHUDText(@"该分类暂无商品");
        }
        // 无论是否有商品都更新左侧选中状态
        [self.leftTableView selectRowAtIndexPath:indexPath
                                       animated:YES
                                 scrollPosition:UITableViewScrollPositionMiddle];
    }
}

#pragma mark - UIScrollViewDelegate (滚动关联)

// 右侧表格滚动时更新左侧选择
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.rightTableView && !self.isRightScrollTriggeredByLeft) {
        // 获取当前显示的所有section
        NSArray *indexPaths = [self.rightTableView indexPathsForVisibleRows];
        
        if (indexPaths.count == 0) return;
        
        // 获取第一个可见的section
        NSInteger section = [[indexPaths firstObject] section];
        
        // 更新左侧表格的选择
        NSIndexPath *selectionIndexPath = [NSIndexPath indexPathForRow:section inSection:0];
        [self.leftTableView selectRowAtIndexPath:selectionIndexPath
                                       animated:YES
                                 scrollPosition:UITableViewScrollPositionMiddle];
    }
}

// 滚动结束处理
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if (scrollView == self.rightTableView) {
        self.isRightScrollTriggeredByLeft = NO;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate && scrollView == self.rightTableView) {
        self.isRightScrollTriggeredByLeft = NO;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.rightTableView) {
        self.isRightScrollTriggeredByLeft = NO;
    }
}

@end
